<?php
namespace App\Admin\Forms;
use Dcat\EasyExcel\Excel;
use Dcat\Admin\Widgets\Form;
use App\Models\Dealer;
use App\Models\VehicleSeries;

class DealerImportForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $file_path = storage_path('app/public' . $input['import_file']);

        // 读取excel文件
        $data = Excel::import($file_path)->toArray();
        
        // [
        //     "Sheet1" => [
        //         2 => [
        //             "姓名" => "张三",
        //             "电话" => 123456789,
        //         ],
        //         3 => [
        //             "姓名" => "李四",
        //             "电话" => 987654321,
        //         ],
        //     ],
        // ]

        // 处理数据
        $rows = $data['Sheet1'];
        $arr = [];
        $series_dealers = [];
        foreach ($rows as $row) {
            $arr[] = [
                'code' => $row['code'],
                'name' => $row['name'],
                'area_code' => $row['area_code'],
                'address' => $row['address'],
                'lat' => $row['lat'],
                'lng' => $row['lng'],
                'level' => $row['level'],
                'service_phone' => $row['service_phone'],
            ];
            $series = explode('|',$row['series_dealers']);
            foreach($series as $r){
                $series_dealers[$r][] = $row['code'];
            }
        }

        Dealer::upsert($arr,['code'],['name','area_code','address','lat','lng','level','service_phone']);

        foreach($series_dealers as $kk=>$rr){

            $ids = Dealer::whereIn('code',$rr)->pluck('id')->toArray();
            VehicleSeries::find($kk)->associatedShop($ids);
        }

        return $this->response()->success('导入成功')->refresh();
    }
    /**
     * Build a form here.
     */
    public function form()
    {
        // 禁用重置表单按钮
        $this->disableResetButton();
        // 文件上传
        $this->file('import_file', ' ')
            ->disk('public')
            ->accept('xls,xlsx')
            ->uniqueName()
            ->autoUpload()
            ->move('/import')
            
            ->help('支持xls,xlsx');

    }
}